<?php
declare (strict_types = 1);

namespace app\command;

use app\common\service\finance\merchant\BalanceService;
use app\model\AgentMerchantStat;
use app\ymsh\model\Agent;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

class YmshStat extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('ymshstat')
            ->setDescription('the ymshstat command');
    }

    protected function execute(Input $input, Output $output)
    {


//        $merchant_id = input('merchant_id');

        //先把相关佣金日期统计成上个月的，顺延

        Agent::query()->whereNotNull('merchant_id')->select()->each(function (Agent $agent){

            try {
                Db::startTrans();

                //先统计
                (new BalanceService())->statByMerchantId($agent->merchant_id);

                //再从数据库拉取
                $agentMerchantStat = AgentMerchantStat::with('agentMerchantStatItem')->where('merchant_id',$agent->merchant_id)
                    ->where('status',AgentMerchantStat::STATUS_WAIT)
                    ->select();

                Db::commit();

            echo '成功结算一单';

            }catch (\Exception $exception){
                Db::rollback();
                Log::error($exception->getMessage());
                Log::error($exception->getFile());
                Log::error($exception->getLine());
                return fail();
            }
        });

    }
}
